package cn.sonui.onlinechat.utils;

import cn.sonui.onlinechat.bean.MessageInfo;
import cn.sonui.onlinechat.bean.RoomInfo;
import cn.sonui.onlinechat.bean.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class OnlineChat {
    public static final Map<Integer, RoomInfo> roomCache = new ConcurrentHashMap<>();//房间列表
    public static final Map<Integer, UserInfo> userCache = new ConcurrentHashMap<>();//用户列表
    public static final Map<String, Integer> livingCache = new ConcurrentHashMap<>();//在线用户列表
    public static final MessageList msgCache = new MessageList();//消息列表
    private static final Logger logger = LoggerFactory.getLogger(OnlineChat.class);
    public void init(){
        /*创建初始用户***/
        UserInfo admin = new UserInfo(
                "Sonui",
                1,
                "o(=•ェ•=)m",
                "abc",
                new ArrayList<>()
        );
        userCache.put(1, admin);

        /*创建全初始消息**/
        MessageInfo hello = new MessageInfo(
                0,
                0,
                "欢迎大家使用在线聊天室",
                1
        );
        Integer msgId = msgCache.addMessage(hello);
        /*创建初始局房间*/
        RoomInfo self = new RoomInfo(
                "大厅",
                1,
                new ArrayList<>(1),
                new ArrayList<>(msgId)
        );
        roomCache.put(1, self);
    }
    public static void sendMessageToRoom(Integer roomId, MessageInfo msg){
        logger.info(String.format(
                "[%s] sendTo Room[%d]: %s",
                (userCache.get(msg.getSender())).getName(),
                roomId,
                msg.getMessage()
                ));

        List<Integer> living = (roomCache.get(roomId)).getMember();
        living.forEach(
                (sid) -> sendMessage(sid, msg)
        );
    }


    public static void sendMessage(Integer sid, MessageInfo msg){
        Session session = (userCache.get(sid)).getSession();
        if(session.isOpen())//判断是否在线
            session.getAsyncRemote().sendText(msg.toString());
        else {
            //当前用户不在线，移除
            logger.info(String.format(
                    "[%d] not online, server will remove this session",
                    sid
                    ));
            userCache.remove(sid);
        }

    }
}
